package permissions

import (
	"context"
	"errors"
	"product/common/datetime"
	"product/common/validator"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePermissionsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 修改权限
func NewUpdatePermissionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePermissionsLogic {
	return &UpdatePermissionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePermissionsLogic) UpdatePermissions(req *types.UpdatePermissionReq) (resp *types.UpdatePermissionResp, err error) {
	if ok, err := validUpdatePermissionsInput(req); !ok {
		return nil, err
	}
	updateFields := make(map[string]interface{})
	if !validator.IsEmptyString(req.Name) {
		updateFields["PermissionName"] = req.Name
	}
	if req.Value > 0 {
		updateFields["PermissionValue"] = req.Value
	}
	if !validator.IsEmptyString(req.Desc) {
		updateFields["Description"] = req.Desc
	}
	if len(updateFields) <= 0 {
		return &types.UpdatePermissionResp{
			Message: "没有需要更新字段",
			Ok:      true,
		}, nil
	}
	updateFields["UpdatedAt"] = datetime.GetNowTimestamp()
	flag, err := l.svcCtx.PermissionsModel.ModifyPermissions(l.ctx, req.Id, updateFields)
	if err != nil {
		return &types.UpdatePermissionResp{
			Message: "更新失败: " + err.Error(),
			Ok:      false,
		}, nil
	}
	return &types.UpdatePermissionResp{
		Message: "更新成功",
		Ok:      flag,
	}, nil
}

func validUpdatePermissionsInput(req *types.UpdatePermissionReq) (bool, error) {
	if req.Id <= 0 {
		return false, errors.New("id不能小于等于0")
	}
	return true, nil
}
